package com.carey.blog.fix;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.carey.blog.framework.latke.action.util.PageCaches;
import com.carey.blog.model.Preference;
import com.carey.blog.util.Preferences;
import com.google.appengine.api.mail.MailService;
import com.google.appengine.api.mail.MailService.Message;
import com.google.appengine.api.mail.MailServiceFactory;

/**
 * Restores the signs of preference to default.
 * 
 */
public final class RestoreSigns extends HttpServlet {

	/**
	 * Default serial version uid.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger.getLogger(RestoreSigns.class
			.getName());
	/**
	 * Preference utilities.
	 */
	private Preferences preferenceUtils = Preferences.getInstance();
	/**
	 * Mail service.
	 */
	private static final MailService MAIL_SVC = MailServiceFactory
			.getMailService();

	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		final PrintWriter writer = response.getWriter();

		try {
			final JSONObject preference = preferenceUtils.getPreference();
			final String originalSigns = preference.getString(Preference.SIGNS);
			preference.put(Preference.SIGNS, Preference.Default.DEFAULT_SIGNS);

			preferenceUtils.setPreference(preference);

			final Message msg = new MailService.Message(
					preference.getString(Preference.ADMIN_EMAIL),
					"DL88250@gmail.com", "Restore signs", originalSigns);
			MAIL_SVC.send(msg);
			writer.println("Restores signs succeeded.");

			PageCaches.removeAll();
		} catch (final Exception e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);
			writer.println("Restores signs failed, error msg[" + e.getMessage()
					+ "]");
		}

		writer.close();
	}
}
